package com.yasenagat.zkweb.service;

import com.google.common.collect.Lists;
import com.yasenagat.zkweb.entity.Customer;
import com.yasenagat.zkweb.repo.CustomerRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.ListUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.awt.*;


@Service
public class ZkQueryServiceImpl implements ZkQueryService{

    @Resource
    CustomerRepository customerRepository;



    @Override
    public Page<Customer> findCustomerNoCriteria(Integer page, Integer size) {

        Pageable pageable = new PageRequest(page, size, Sort.Direction.ASC, "id");
        return customerRepository.findAll(pageable);
    }

    @Override
    public Page<Customer> findCustomerCriteria(Integer page, Integer size, Customer customer) {
        Pageable pageable = new PageRequest(page, size, Sort.Direction.ASC, "id");

        Page<Customer> customerPage = customerRepository.findAll(new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate p1 = criteriaBuilder.like(root.get("id").as(String.class),String.valueOf(customer.getId()));
                Predicate p2 = criteriaBuilder.like(root.get("name").as(String.class),customer.getName());
                Predicate p3 = criteriaBuilder.like(root.get("address").as(String.class),customer.getAddress());
                criteriaQuery.where(criteriaBuilder.and(p1,p2,p3));
                return criteriaQuery.getRestriction();
            }
        },pageable);

        return customerPage;
    }

    @Override
    public int totalCount() {
        if(ListUtils.isEmpty(customerRepository.findAll())){
            return 0;
        }
        return customerRepository.findAll().size();
    }
}
